import babelpolyfill from 'babel-polyfill'
import Vue from 'vue'
import App from './App'

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css';

import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'

//引入axios
import axios from "axios";
//axios的基础路径
axios.defaults.baseURL="http://localhost:8080";
//全局axios属性
Vue.prototype.$http=axios;


import routes from './routes'

import 'font-awesome/css/font-awesome.min.css'

Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(Vuex)

//NProgress.configure({ showSpinner: false });

const router = new VueRouter({
  routes
})
//1.axios前置拦截器：每次通过axios发送请求之前，让所有的请求都携带uToken
axios.interceptors.request.use(config=>{
  //从localStorage中获取token
  let token =  localStorage.getItem("token");
  //如果有值
  if(token){
    //将token设置到请求头
    config.headers['token']=token;
  }
  return config;
},error => {
  Promise.reject(error);
})
//2.axios后置拦截器：后端处理完axios请求之后，处理响应的数据
axios.interceptors.response.use(res=>{
  let data = res.data;
  if (false === data.success && "noLogin" === data.msg) {
    localStorage.removeItem("token");
    localStorage.removeItem("logininfo");
    router.push({path: '/login'});
  }
  if (false === data.success && "noPermission" === data.msg) {
      alert("你没有该权限访问")
      return
  }
  return res;
},error => {
  Promise.reject(error);
})
//3.路由拦截器,只要是通过路由的请求都会执行下面的代码
router.beforeEach((to, from, next) => {
  if (to.path == '/login' || to.path == '/register' ) {
    next();
  }else{//访问其他页面 - 判断是否登录过 - logininfo
    let logininfo = JSON.parse(localStorage.getItem('logininfo'));
    if(logininfo){
      next();
    }else{//访问的不是登录页面，页不是注册页面。没有登录
      next({ path: '/login' })
    }
  }
})
//发送路由的每一个请求之前
/*router.beforeEach((to, from, next) => {
  //NProgress.start();
  if (to.path == '/login') {
    sessionStorage.removeItem('user');
  }
  let user = JSON.parse(sessionStorage.getItem('user'));
  if (!user && to.path != '/login') {
    next({ path: '/login' })
  } else {
    next()
  }
})*/

//router.afterEach(transition => {
//NProgress.done();
//});

new Vue({
  //el: '#app',
  //template: '<App/>',
  router,
  store,
  //components: { App }
  render: h => h(App)
}).$mount('#app')

